<template>
  <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
    <el-tab-pane label="促销信息" name="first">
      <div class="promotion" v-loading.fullscreen.lock="fullscreenLoading">
        <!--查询-->
        <el-form :inline="true">
          <el-form-item label="查询">
            <el-input
              v-model="searchWords"
              placeholder="请输入商家名称"
              icon="close"
              :on-icon-click="searchCancleClick"></el-input>
          </el-form-item>
          <el-button type="primary" @click="searchVendor">查询</el-button>
          <el-button type="success" @click="addVendor">新增</el-button>
        </el-form>
        <!--列表-->
        <el-table ref="multipleTable" border
                  tooltip-effect="dark"
                  :default-sort="{prop: 'id', order: 'descending'}"
                  :data="viewListData"
                  @selection-change="handleSelectionChange">
          <el-table-column prop="id" label="ID" width="100px" sortable></el-table-column>
          <el-table-column prop="name" label="名称" width="180px"></el-table-column>
          <el-table-column prop="rebate" label="基础返利" width="140px"></el-table-column>
          <el-table-column prop="rights" label="线上餐厅列表显示会员权益内容"></el-table-column>
          <el-table-column prop="imgUrl" label="图片" width="100px">
            <template scope="scope">
              <img class="img-url" :src="scope.row.imgUrl">
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150px">
            <template scope="scope">
              <el-button type="" size="small" @click="editItem(scope.$index, scope.row)">编  辑</el-button>
              <el-button type="danger" size="small" @click="deleteItem(scope.$index, scope.row)">删  除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!--增、改弹窗-->
        <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible">
          <el-form :model="addEditItem" :rules="formRules" ref="dialogPromotionForm">
            <el-form-item label="ID" :label-width="dialogLabelWidth" prop="id">
              <el-input v-model="addEditItem.id"></el-input>
            </el-form-item>
            <el-form-item label="名称" :label-width="dialogLabelWidth" prop="name">
              <el-input v-model="addEditItem.name"></el-input>
            </el-form-item>
            <el-form-item label="基础返利" :label-width="dialogLabelWidth" prop="rebate">
              <el-input type="textarea" v-model="addEditItem.rebate"></el-input>
            </el-form-item>
            <el-form-item label="线上餐厅列表显示会员权益内容" :label-width="dialogLabelWidth" prop="rights">
              <el-input type="textarea" v-model="addEditItem.rights"></el-input>
            </el-form-item>
            <!-- <el-form-item label="图片地址" :label-width="dialogLabelWidth">
              <el-input type="textarea" v-model="addEditItem.imgUrl"></el-input>
            </el-form-item> -->
            <el-form-item>
              <div class="dialog-form-btn">
                <el-button type="success" size="small" @click="saveData('dialogPromotionForm')">保  存</el-button>
                <el-button type="" size="small" @click="dialogCancel">取  消</el-button>
              </div>
            </el-form-item>
          </el-form>
        </el-dialog>
        <!--分页-->
        <div class="page-handle">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page.sync="currentPage"
            :page-size="pageSize"
            layout="prev, pager, next, jumper"
            :total="total">
          </el-pagination>
        </div>
      </div>
    </el-tab-pane>
    <el-tab-pane class="banner-config" label=" Banner管理" name="second">
      <el-button class="addBannerBtn" size="small" type="success" @click="addBannerClick">新增</el-button>
      <el-table border stripe v-if="bannerList" :data="bannerList" style="width:50%">
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="imageUrl" label="图片地址">
          <template scope="scope">
            <img class="preview-img" :src="scope.row.imageUrl" alt="">
          </template>
        </el-table-column>
        <el-table-column prop="linkUrl" label="链接地址">
          <template scope="scope">
            {{scope.row.linkUrl}}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template scope="scope">
            <el-button type="primary" size="small" @click="editBannerClick(scope.$index,scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="deleteBannerClick(scope.$index,scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog :title="bannerAddFlag?'新增':'修改'" :visible.sync="dialogBannerFormVisible">
        <el-form :model="bannerData">
          <el-form-item label="链接地址">
            <el-input v-model="bannerData.imageUrl" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="跳转链接">
            <el-input v-model="bannerData.linkUrl" auto-complete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancelBannerDialog">取 消</el-button>
          <el-button v-if="bannerAddFlag" type="primary" @click="bannersAddRequest">新 增</el-button>
          <el-button v-else type="primary" @click="bannersEditRequest">修 改</el-button>
        </div>
      </el-dialog>
    </el-tab-pane>
  </el-tabs>
</template>

<script>
  import axios from 'axios'
  const promotionCtrlUrl = '/node/api/promotion'
  const bannerCtrlUrl = '/node/api/restaurant/banner'
  export default{
    data () {
      return {
        activeName: 'first',
        bannerList: [], // 颁娜儿
        bannerData: {
          imageUrl: '',
          linkUrl: ''
        },
        bannerAddFlag: false,
        dialogBannerFormVisible: false,
        promotionData: [],
        viewListData: [], // 当前显示数据
        searchWords: '',
        pageSize: 10,
        currentPage: 1,
        total: null,
        dialogFormVisible: false,
        addEditItem: {},
        addFlag: false,
        dialogTitle: '新增',
        dialogLabelWidth: '120px',
        fullscreenLoading: false,
        formRules: {
          id: [{required: true, message: '请输入ID', trigger: 'change'}],
          name: [{required: true, message: '请输入名称', trigger: 'change'}],
          rebate: [{required: false, message: '请输入基础返利', trigger: 'change'}],
          rights: [{required: false, message: '请输入线上餐厅列表显示会员权益内容', trigger: 'change'}]
        }
      }
    },
    mounted () {
      this.requestData()
    },
    computed: {},
    methods: {
      // 标签切换后请求颁娜儿数据
      handleClick (tab, event) {
        if (tab.name === 'second' && this.bannerList.length === 0) {
          this.bannersRequest()
        }
      },
      // 请求数据
      requestData () {
        this.fullscreenLoading = true
        axios.get(promotionCtrlUrl).then((res) => {
          this.promotionData = res.data.result
          this.viewListData = this.promotionData.slice(0, this.pageSize)
          this.total = this.promotionData.length
          this.fullscreenLoading = false
        })
      },
      // 修改、新增数据
      saveData (formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (this.addFlag === false) {
              axios.put(promotionCtrlUrl, this.addEditItem).then((res) => {
                if (res.data.nModified === 1) {
                  this.$message({
                    message: '恭喜你，修改成功',
                    type: 'success'
                  })
                  this.dialogFormVisible = false
                }
              })
            } else if (this.addFlag === true) {
              axios.post(promotionCtrlUrl, this.addEditItem).then((res) => {
                if (res.data) {
                  this.addFlag = false
                  this.$message({
                    message: '恭喜你，新增成功',
                    type: 'success'
                  })
                  this.dialogFormVisible = false
                }
              })
            }
            this.requestData()
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      // 删除数据
      deleteData (id) {
        axios.delete('/node/api/promotion/' + id).then((res) => {
          if (res.data.n === 1 && res.data.ok === 1) {
            this.$message({
              message: '恭喜你，删除成功！',
              type: 'success'
            })
            this.requestData()
          }
        })
      },
      // 关闭搜索内容
      searchCancleClick () {
        this.searchWords = ''
        this.requestData()
      },
      // 关闭对话框
      dialogCancel () {
        this.dialogFormVisible = false
      },
      // 查询商家
      searchVendor () {
        axios.get('/node/api/promotion-name?name=' + this.searchWords).then(res => {
          this.promotionData = res.data
          this.viewListData = this.promotionData.slice(0, this.pageSize)
          this.total = this.promotionData.length
        })
      },
      // 新增商家--click
      addVendor () {
        this.dialogTitle = '新增'
        this.addFlag = true
        this.dialogFormVisible = true
        this.addEditItem = {}
      },
      // 删除商家信息
      deleteItem (index, row) {
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.deleteData(row.id)
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      // 编辑商家信息
      editItem (index, row) {
        this.dialogTitle = '编辑'
        this.dialogFormVisible = true
        this.addEditItem = row
        this.addFlag = false
      },
      // TODO: 多选
      handleSelectionChange () {
      },
      // 分页控制
      handleCurrentChange (val) {
        this.currentPage = val
        let startPos = (this.currentPage - 1) * this.pageSize
        let endPos = (this.currentPage) * this.pageSize
        this.viewListData = this.promotionData.slice(startPos, endPos)
      },
      // TODO: 分页容量
      handleSizeChange (val) {
        console.log(val)
      },
      /* ----颁娜儿----- */
      // 颁娜儿数据请求
      bannersRequest () {
        axios.get(bannerCtrlUrl).then(res => {
          this.bannerList = res.data
        })
      },
      bannersAddRequest () {
        if (this.bannerData.imageUrl !== null && this.bannerData.imageUrl !== '') {
          axios.post(bannerCtrlUrl, this.bannerData).then(res => {
            console.log(res)
            if (res.data.imageUrl === this.bannerData.imageUrl) {
              this.$notify({
                title: '成功',
                message: '增加成功！',
                type: 'success'
              })
              this.bannersRequest()
              this.bannerData = {}
              this.dialogBannerFormVisible = false
            }
          })
        } else {
          this.$notify({
            title: '警告',
            message: '不能为空',
            type: 'warning'
          })
        }
      },
      bannersEditRequest () {
        axios.put(bannerCtrlUrl, this.bannerData).then(res => {
          if (res.data.nModified === 1) {
            this.$notify({
              title: '成功',
              message: '编辑成功！',
              type: 'success'
            })
            this.bannersRequest()
            this.bannerData = {}
            this.dialogBannerFormVisible = false
          }
        })
      },
      cancelBannerDialog () {
        this.dialogBannerFormVisible = false
        this.bannerAddFlag = false
        this.bannerData = {}
      },
      editBannerClick (idx, row) {
        this.bannerAddFlag = false
        this.dialogBannerFormVisible = true
        this.bannerData = row
      },
      addBannerClick () {
        this.bannerAddFlag = true
        this.dialogBannerFormVisible = true
      },
      deleteBannerClick (idx, row) {
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          axios.delete(bannerCtrlUrl + '/' + row._id).then(res => {
            if (res.data.n === 1) {
              this.$notify({
                title: '成功',
                message: '删除成功！',
                type: 'success'
              })
              this.bannersRequest()
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }
    }
  }
</script>

<style lang="less" rel="stylesheet/less">
  .promotion {
    .img-url {
      width: 70px;
      height: 70px;
    }
    .page-handle, .dialog-form-btn {
      text-align: center;
      margin-top: 20px;
    }
  }

  .banner-config {
    .preview-img {
      width: 100px;
      height: 70px;
    }
    .addBannerBtn {
      margin-bottom: 30px;
    }
  }
</style>
